//
//  MainViewController.swift
//  TYHWeibo
//
//  Created by IOS on 15/7/28.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
        //此时TabBarButton还没有创建
        print(tabBar.subviews)
        
    }
    
    override func viewDidAppear(animated: Bool) {
        setupComposedButton()
        
    }
    
    func clickComposedButton() {
//        print(__FUNCTION__)
        let vc = UserAccount.userLogin ? ComposeViewController() : OAuthViewController()
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true, completion: nil)
        
    }
    
    //设置撰写按钮位置
    private func setupComposedButton(){
        let w = tabBar.bounds.width / CGFloat(viewControllers!.count)
        let rect = CGRect(x: 0, y: 0, width: w, height: tabBar.bounds.height)
        composeButten.frame = CGRectOffset(rect, 2 * w, 0)
    }
    
    //添加所有子控制器
    private func addChildViewControllers() {
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DIscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    //添加子控制器
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        
        tabBar.tintColor = UIColor.orangeColor()
        //title 属性从内向外传递设置
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
        
    }
    //懒加载
    lazy private var composeButten: UIButton = {
        let butten = UIButton()
        butten.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        butten.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        butten.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        butten.setBackgroundImage(UIImage(named: "tabbar_compose_button_hightlighted"), forState: UIControlState.Highlighted)
        
        self.tabBar.addSubview(butten)
        butten.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
        return butten
    }()
    

}
